package com.sk.waste.app.activitys

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.lc.smc.lib.views.pulllayout.SKPullRefresh
import com.lc.smc.lib.views.pulllayout.SKPullRefreshLayout
import com.sk.waste.app.R
import com.sk.waste.app.adapters.TenderAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.MaterialModel
import com.sk.waste.app.models.TenderModel
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.views.DistrictPopuWindow
import com.sk.waste.app.views.TypePopuWindow
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException


/**
 *  @time 2025/4/25  17:11
 *  @desc 生意分类
 */
class ClassifyActivity : BaseActiivity() {

    @LCBindView(R.id.view_search_text)
    private lateinit var ettSearch: EditText

    @LCBindView(R.id.view_search_butt)
    private lateinit var bttSearch: Button

    @LCBindView(R.id.ac_classify_tablayout)
    private lateinit var tabLayout: TabLayout

    @LCBindView(R.id.ac_classify_district)
    private lateinit var ttvDistrict: TextView

    @LCBindView(R.id.ac_classify_type)
    private lateinit var ttvType: TextView

    @LCBindView(R.id.ac_classify_recyclerview)
    private lateinit var recyclerView: RecyclerView

    @LCBindView(R.id.ac_classify_interest)
    private lateinit var bttInterest: TextView

    @LCBindView(R.id.ac_swipe_refreshLayout)
    private lateinit var pullRefreshLayout: SKPullRefreshLayout

    private val tablist = ArrayList<MaterialModel>()

    private lateinit var tenderAdapter: TenderAdapter
    private var tenderList = ArrayList<TenderModel>()

    private lateinit var districtPopuWindow: DistrictPopuWindow
    private lateinit var typePopuWindow: TypePopuWindow

    private var currentLabName = ""
    private var currentLabId = "" //当前选中的大类id
    private var currentSubId = "" //当前选中的小类id
    private var currentDistrict = "" //当前城市

    //    private var searchStr = "" //当前搜索
    private var currentPage = 1
    val userinfo = MyApplication.instance.getUserInfo()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_classity)
        super.onCreate(savedInstanceState)
        setTitleColorLight(false)
        setBack()
        setTitleView("生意")
        initAdapter()
        initPopuwindow()
        initTablayout()
        initTypeSpinner()

        ttvDistrict.setOnClickListener {
            if (typePopuWindow.isShowing) {
                typePopuWindow.dismiss()
            }
            if (districtPopuWindow.isShowing) {
                districtPopuWindow.dismiss()
            } else {
                val location = IntArray(2)
                ttvDistrict.getLocationOnScreen(location)
                districtPopuWindow.showAtLocation(ttvDistrict, Gravity.CENTER, 0, location[1] + ttvDistrict.height + 5)
            }
        }

        ttvType.setOnClickListener {
            if (districtPopuWindow.isShowing) {
                districtPopuWindow.dismiss()
            }
            if (typePopuWindow.isShowing) {
                typePopuWindow.dismiss()
            } else {
                val location = IntArray(2)
                ttvType.getLocationOnScreen(location)
                typePopuWindow.showAtLocation(ttvDistrict, Gravity.CENTER, 0, location[1] + ttvType.height + 5, currentLabId)
            }
        }
        bttSearch.setOnClickListener {
//            searchStr = ettSearch.text.toString()
            currentPage = 1
            hideKeyboard()
            getTenderList()
        }
        ettSearch.setOnEditorActionListener { v, actionId, event -> // 在这里处理搜 索逻辑
            // 返回 true 表示你已经处理了这个事件
            currentPage = 1
            getTenderList()
            true
        }

        bttInterest.setOnClickListener {
            val intent = Intent(mContext, InterestActivity::class.java)
            activityResultLauncher.launch(intent)
        }

    }

    val activityResultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult())
    { result: ActivityResult ->
        if (result.resultCode == RESULT_OK) {
            val data = result.data
            val str = data?.getStringExtra("extral_str")
            if (!LCBaseUtil.isNull(str)) {
//                searchStr = str!!
                ettSearch.setText(str!!)
                getTenderList()
            }
        }
    }


    /**
     *  @time 2025/4/25  14:37
     *  @desc 初始化tablayout
     */
    private fun initTablayout() {
        currentLabName = intent.getStringExtra("extral_labname") as String
        currentLabId = intent.getStringExtra("extral_labcode") as String
        if (LCBaseUtil.isNull(currentLabName)) {
            getMaterialList()
        } else {
            tablist.add(MaterialModel().apply {
                categoryName = currentLabName
                id = currentLabId
            })
            setTabLayout()
        }
        pullRefreshLayout.onStartListener = refreshListener
        pullRefreshLayout.onStartListener.onStartRefresh(pullRefreshLayout)
//        judgeVip()
    }


    private fun setTabLayout() {
        currentLabId = tablist[0].id
        typePopuWindow.getSubMaterialList(currentLabId)
        for (item in tablist) {
            val tabItem = tabLayout.newTab().apply { text = item.categoryName }
            tabLayout.addTab(tabItem)
        }

        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                currentLabId = tablist[tab.position].id
                if (districtPopuWindow.isShowing) {
                    districtPopuWindow.dismiss()
                }
                if (typePopuWindow.isShowing) {
                    typePopuWindow.dismiss()
                }
                currentPage = 1
                currentSubId = ""
                getTenderList()
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
            }

            override fun onTabReselected(tab: TabLayout.Tab) {}
        })
    }

    /**
     *  @time 2025/4/28  15:13
     *  @desc 政区
     */
    private fun initPopuwindow() {

        districtPopuWindow = DistrictPopuWindow()
        districtPopuWindow.init(this)
        districtPopuWindow.setPopuOnclickListener(object : LCInterface.LcCallBack {
            override fun callBack(vararg args: Any?) {
                val district = args[0] as String
                currentDistrict = district
                currentPage = 1
                getTenderList()
            }
        })

        typePopuWindow = TypePopuWindow()
        typePopuWindow.init(this)
        typePopuWindow.setPopuOnclickListener(object : LCInterface.LcCallBack {
            override fun callBack(vararg args: Any?) {
                val subId = args[0] as String
                currentSubId = subId
                currentPage = 1
                getTenderList()
            }
        })
    }

    /**
     *  @time 2025/4/28  17:15
     *  @desc 分类spinner
     */
    private fun initTypeSpinner() {
//        val adapter = ArrayAdapter(this, R.layout.view_spinner_item, listType) // 使用自定义布局
//        adapter.setDropDownViewResource(R.layout.view_spinner_item_dropdown)
//        spinnerType.adapter = adapter

    }

    private fun initAdapter() {
        recyclerView.layoutManager = LinearLayoutManager(mContext)
        tenderAdapter = TenderAdapter(mContext, 0, tenderList, mOnItemClickListener)
        recyclerView.adapter = tenderAdapter
    }

    private val mOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val postion = args[1] as Int
            val intent = Intent(mContext, SyDetailActivity::class.java)
            intent.putExtra("tender_id", tenderList[postion].id)
            startActivity(intent)
        }
    }


    /**
     *  @time 2024/5/7  11:29
     *  @desc 分类 - 大类
     *  @param url
     */
    private fun getMaterialList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_ALLMATERIAL
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", "100")
        params.put("pageNo", "1")
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONArray("data")
                    tablist.clear()
                    tablist.add(MaterialModel().apply {
                        categoryName = "全部分类"
                    })
                    if (success) {
                        for (index in 0 until data.length()) {
                            val item = MaterialModel().apply { getModelInfo(data.getJSONObject(index)) }
                            tablist.add(item)
                        }
                        runOnUiThread { setTabLayout() }
                        LCLogger.d(TAG, "获取成功！,数据：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                }
            }
        })
    }

    private val refreshListener = object : SKPullRefresh.OnStartListener {
        override fun onStartRefresh(p0: SKPullRefresh?) {
            currentPage = 1
            getTenderList()
        }

        override fun onStartLoadmore(p0: SKPullRefresh?) {
            if (userinfo!!.isVip()) {
                currentPage++
                getTenderList()
            } else {
                currentPage = 1
                pullRefreshLayout.loadmoreSuccess()
            }
        }

    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 生意列表
     *  @param url
     */
    private fun getTenderList() {
        if (currentPage == 1) {
            showProgress()
            tenderList.clear()
            tenderAdapter.notifyDataSetChanged()
        }
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_SYLIST
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", AppConfig.PAGE_SIZE)
        params.put("pageNo", currentPage)
        var filter = ""
        if (currentDistrict.isNotEmpty()) {
            filter = currentDistrict
        }
        val searchStr = ettSearch.text.toString().trim()
        if (searchStr.isNotEmpty()) {
            if (filter.isEmpty()) {
                filter = searchStr
            } else {
                filter = "$filter,$searchStr"
            }
        }
        params.put("contentText", filter)
        params.put("categoryIds", currentLabId)
        params.put("subcategoryIds", currentSubId)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                freshOrLoadFaild()
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    val rows = data.getJSONArray("rows")
                    if (success) {
                        runOnUiThread {
                            fresOrLoadSuccess(rows.length())
                            for (index in 0 until rows.length()) {
                                val item = TenderModel().apply { getModelInfo(rows.getJSONObject(index)) }
                                tenderList.add(item)
                            }
//                            judgeVip()
                            tenderAdapter.notifyDataSetChanged()
                        }
                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        freshOrLoadFaild()
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    freshOrLoadFaild()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                    Log.e("LCLOG_ERROR", e.toString())
                }
            }
        })
    }

    private fun fresOrLoadSuccess(rows: Int) {
        if (1 == currentPage) { // 刷新
            pullRefreshLayout.refreshSuccess()
            tenderList.clear()
        } else {
            pullRefreshLayout.loadmoreSuccess()
        }
        if (rows == AppConfig.PAGE_SIZE) {
            pullRefreshLayout.isLoadmoreable = true
        } else {
            pullRefreshLayout.isLoadmoreable = false
        }
    }

    private fun freshOrLoadFaild() {
        runOnUiThread {
            if (currentPage == 1) {
//            pullRefreshLayout.stopRefresh()
//                pullRefreshLayout.refreshSuccess();
                pullRefreshLayout.refreshFailed();
            } else {
//                pullRefreshLayout.loadmoreSuccess()
                pullRefreshLayout.loadmoreFailed()
            }
        }
    }

}